class User < ActiveRecord::Base
  belongs_to :group

  validates_uniqueness_of :email
  before_create :encrypt_password, :make_activation_code

  def full_name(last_first = true)
    if last_first
      "#{surname}#{firstname}"
    else
      "#{firstname} #{surname}"
    end
  end
  
  # Authenticates a user by their login name and unencrypted password.  Returns the user or nil.
  def self.authenticate(email, password)
    # use this instead if you want user activation
    encrypted_pass = Digest::MD5.hexdigest("--my-salt--#{password}")
    #u = find :first, :select => 'email', :conditions => 
    #                    ['email = ? AND status > 0 AND password = ?', email, encrypted_pass]
    u = find :first, :conditions => 
                    ['email = ? AND status > 0 AND password = ?', email, encrypted_pass]
  end

  def to_s
    'id=' + self.id.to_s + ', email=' + self.email
  end

  protected
    # we use MD5 for password encryption
    def md5(pass)
      Digest::MD5.hexdigest("--my-salt--#{pass}")
    end

    def encrypt_password
      return if password.blank?
      self.password = md5(password)
    end

    def make_activation_code
      self.activation_code = md5(Time.now.to_s)
    end
end